﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OMG.Fill.Vegetable.Model;
using OMG.Fill.Vegetable.Model.Ent;
using OMG.Fill.Vegetable.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;

namespace OMG.Fill.Vegetables.UI
{
    public class ApiActionAuthorize : AuthorizeAttribute
    {
        private string actionName { get; set; }
        public ApiActionAuthorize(string strActionName) {
            actionName = strActionName;
        }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("HttpActionContext");
            }
            else
            {
                if (actionContext.Request.Headers.GetCookies().Count() != 0)
                {
                    string strRequestUrl = "/" + actionContext.ActionDescriptor.ControllerDescriptor.ControllerName + "/" + actionContext.ActionDescriptor.ActionName;
                    var cookieValue = actionContext.Request.Headers.GetCookies().FirstOrDefault().Cookies.Where(p => p.Name == FormsAuthentication.FormsCookieName).FirstOrDefault().Value;
                    if (cookieValue == null)
                        return false;
                    else
                    {
                        LogsServices logServices = new LogsServices();
                        logServices.AddInfo(new LogsEntity { Account=AppUser.GetUser().Account,ActionCode=strRequestUrl,ActionName=actionName,LogsTime=DateTime.Now,IpAddress= GetIP() });
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }

        }
        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public string GetIP()
        {
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            if (string.IsNullOrEmpty(result))
            {
                return "127.0.0.1";
            }
            return result;
        }
    }
}